<?php

namespace app\admin\model\customer;

use think\Model;


class Service extends Model
{

    // 表名
    protected $name = 'customer_service';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'create_time_text',
        'start_time_text',
        'end_time_text',
        'distance_days',
    ];

    public function customer()
    {
        return $this->hasOne('Intention', 'id', 'customer_id');
    }

    public function package()
    {
        return $this->belongsTo('Package', 'package_id', 'package_id', [], 'LEFT')->setEagerlyType(0);
    }


    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['create_time']) ? $data['create_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getStartTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['start_time']) ? $data['start_time'] : '');
        return is_numeric($value) ? date("Y-m", $value) : $value;
    }

    public function getEndTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['end_time']) ? $data['end_time'] : '');
        return is_numeric($value) ? date("Y-m", $value) : $value;
    }

    protected function setCreateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    public function getDistanceDaysAttr($value, $data)
    {
        $datetime1 = new \DateTime();
        $datetime2 = new \DateTime(date('Y-m-d', $data['end_time']));
        $interval = $datetime1->diff($datetime2);
        return $interval->m;
    }


}
